﻿
// 创建人  ：LiKun
// 创建时间：2006-09-06
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data.Oracle;
using Common;

namespace ChBusiness
{

    /// <summary>
    /// DataBase的管理类，管理DataBase实例
    /// </summary>
    /// <!--
    /// 创建人  : LiKun
    /// 创建时间: 2006-09-06
    /// -->
    internal static class DataBaseHelper
    {
        //Database字典，保存所有Database
        static private Dictionary<string, Database> _dicDatabase = new Dictionary<string, Database>(StringComparer.InvariantCultureIgnoreCase);

        /// <summary>
        /// 根据配置文件中连接串名称获取DataBase
        /// </summary>
        /// <param name="name">配置文件中连接串名称</param>
        /// <returns>所需Datase</returns>
        /// <!--
        /// 创建人  : LiKun
        /// 创建时间: 2006-09-06
        /// -->
        internal static Database GetDatabase(string name)
        {
            return GetDatabase(ConfigurationManager.ConnectionStrings[name]);
        }

        /// <summary>
        /// 根据配置文件中连接串名称获取DataBase
        /// </summary>
        /// <param name="connectionSetting">配置文件中连接串名称</param>
        /// <returns>所需Datase</returns>
        /// <!--
        /// 创建人  : LiKun
        /// 创建时间: 2006-09-06
        /// -->
        internal static Database GetDatabase(ConnectionStringSettings connectionSetting)
        {
            Database dbTemp = null;
            if (null != connectionSetting)
            {
                if (!string.IsNullOrEmpty(connectionSetting.Name))
                {
                    //锁定Database字典，查看是否已经存在
                    lock (_dicDatabase)
                    {
                        if (_dicDatabase.ContainsKey(connectionSetting.Name))
                        {
                            dbTemp = _dicDatabase[connectionSetting.Name];
                        }
                        else
                        {
                            if (GlobalSetting.IsEncode)
                            {
                                dbTemp = new OracleDatabase(Encode.DesDecrypt(connectionSetting.ConnectionString, GlobalSetting.KeyPass));
                            }
                            else
                            {
                                dbTemp = DatabaseFactory.CreateDatabase(connectionSetting.Name);
                            }
                            _dicDatabase.Add(connectionSetting.Name, dbTemp);
                        }

                    }
                }
            }

            return dbTemp;
        }
    }
}
